package com.tbsoft.ehr.service.user;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.tbsoft.ehr.dao.user.RoleDao;
import com.tbsoft.ehr.login.MenuInfo;
import com.tbsoft.ehr.login.RoleInfo;

public class RoleServiceImpl implements RoleService {
	private RoleDao roleDao;
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	@Override
	public int getRoleCount(RoleInfo role) {
		return roleDao.getRoleCount(role);
	}

	@Override
	public List<RoleInfo> getRoleList(RoleInfo role, int startIndex, int count) {
		return roleDao.getRoleList(role, startIndex, count);
	}
	
	@Override
	public void saveRole(RoleInfo role) {
		roleDao.save(role);
	}
	@Override
	public void deleteRole(RoleInfo role) {
		roleDao.delete(role);
	}
	@Override
	public RoleInfo getRoleById(String id) {
		return roleDao.getRoleById(id);
	}
	@Override
	public List<MenuInfo> getAllMenuList() {
		List<MenuInfo> rootMenuList = roleDao.getMenuListByLvl(1);
		List<MenuInfo> childMenuList = roleDao.getMenuListByLvl(2);
		for(MenuInfo rmi:rootMenuList){
			for(MenuInfo cmi:childMenuList){
				if(cmi.getParentMenuId().equals(rmi.getMenuId())){
					rmi.getChildMenuInfo().add(cmi);
				}
			}
		}
		Collections.sort(rootMenuList,  new Comparator<MenuInfo>(){

			@Override
			public int compare(MenuInfo o1, MenuInfo o2) {
				return o1.getMenuId().compareTo(o2.getMenuId());
			}} );
		return rootMenuList;
	}
	@Override
	public void saveMenuList(RoleInfo role, List<String> menuId) {
		List<MenuInfo> menuList = roleDao.getMenuListByIdList(menuId);
		role = roleDao.getRoleById(role.getRoleId());
		role.getMenuSet().clear();
		if(menuList!=null){
			role.getMenuSet().addAll(menuList);
		}
		roleDao.save(role);
	}
}
